In computer programming, garbage collection (GC) provides automatic memory management. A garbage collector tries to reclaim memory which holds objects that are no longer being used by any program. Garbage collection can free programmers from the need to manually release objects that are no longer needed, making programming easier. Garbage collection can also prevent some runtime errors. Many computer languages require garbage collection, or provide garbage collection as an option. Some languages allow both garbage collection and manual memory management in a given program.
Efficient implementation of garbage collection can be a high priority because garbage collectors may run frequently and at unpredictable times. Garbage collection is often integrated into the programming language's compiler and runtime system. In some cases, garbage collection can be added to an operating environment through libraries. Integrated garbage collection can be an efficient approach, because many garbage collectors operate by tracing connections (pointers, links, handles, references, etc.) between objects, in order to identify objects that cannot be accessed. Then the garbage collector reclaims the memory used by those unreachable objects.
However, in practice a garbage collector's behavior can be more complex. For example, in many programs the most recently created objects are also those most likely to soon become unreachable, so a generational garbage collector divides objects into generations and focuses on the objects in a subset of generations. This focus can provide faster garbage collection while still reclaiming most unreachable objects.
A desire for flexibility can also complicate garbage collector behavior, without diminishing the desire for efficient implementation of garbage collection. For instance, one may want the garbage collection of an object to trigger an action on another object. One may want to build weak caches, with different connections in an object graph having different strengths. One may want to track regions of memory that are used for I/O by memory-mapped devices, so the garbage collector won't unexpectedly change references to such regions.